package cAmqp

import (
	"time"

	"github.com/gin-gonic/gin"
	"github.com/rabbitmq/amqp091-go"

	"gitee.com/csingo/cLog"
)

func basicGet(ctx *gin.Context, channel *amqp091.Channel, driver *AmqpConf_Driver, option ConsumeOption) (err error) {
	var start bool  // 是否开始 循环等待次数 计数
	var count int64 // 循环等待次数
	var msgs []amqp091.Delivery

	defer func() {
		if len(msgs) > 0 {
			runMessageHandlerFunc(ctx, &msgs, option.AutoAck, driver, option.Handler)
		}
	}()

	for {
		if channel.IsClosed() {
			return AmqpChannelCloseErr
		}
		if option.PauseHandler != nil && option.PauseHandler(ctx, option.Params) {
			cLog.WithContext(ctx, map[string]any{
				"source": "cAmqp.basicGet",
				"driver": driver,
			}).Tracef("AMQP 消费者队列暂停消费(BasicGet)，等待 %d 秒后继续", option.WaitTime)
			time.Sleep(time.Duration(option.WaitTime) * time.Second)
			continue
		}
		var msg amqp091.Delivery
		var ok bool
		msg, ok, err = channel.Get(driver.QueueName, option.AutoAck)
		if err != nil {
			cLog.WithContext(ctx, map[string]any{
				"source": "cAmqp.basicGet",
				"driver": driver,
				"err":    err.Error(),
			}).Error("AMQP 消费者读取异常(BasicGet)，重连后后继续")
			return
		}

		if ok {
			count = 0
			start = true
			msgs = append(msgs, msg)
		} else {
			if start {
				count++
			}

			if count <= option.WaitCount+1 {
				cLog.WithContext(ctx, map[string]any{
					"source": "cAmqp.basicGet",
					"driver": driver,
				}).Tracef("AMQP 消费者队列暂无数据(BasicGet)，等待 %d 秒后继续", option.WaitTime)
				time.Sleep(time.Duration(option.WaitTime) * time.Second)
				continue
			}

			if len(msgs) > 0 {
				cLog.WithContext(ctx, map[string]any{
					"source": "cAmqp.basicGet",
					"driver": driver,
				}).Tracef("AMQP 消费者队列暂无数据(BasicGet)，清空缓存数据并等待 %d 秒后继续", option.WaitTime)
				count = 0
				runMessageHandlerFunc(ctx, &msgs, option.AutoAck, driver, option.Handler)
				continue
			}

			// 删除队列
			if option.Queue.AutoDeleted {
				cLog.WithContext(ctx, map[string]any{
					"source": "cAmqp.basicGet",
					"driver": driver,
				}).Trace("AMQP 消费者退出(BasicGet)")
				return
			}

			cLog.WithContext(ctx, map[string]any{
				"source": "cAmqp.basicGet",
				"driver": driver,
			}).Tracef("AMQP 消费者队列暂无数据(BasicGet)，等待 %d 秒后继续", option.WaitTime)
			time.Sleep(time.Duration(option.WaitTime) * time.Second)
		}

		if int64(len(msgs)) >= option.BatchSize {
			runMessageHandlerFunc(ctx, &msgs, false, driver, option.Handler)
		}
	}
}
